<template>
    <div id="push-page">
        <div class="card-container">
            <div class="body-title">
                <div class="body-title-left">快速速报</div>
            </div>
            <el-table :data="flashData" height="102" style="width: 100%">
                <el-table-column label="震中地名" min-width="150" show-overflow-tooltip align="center" prop="locname">
                </el-table-column>
                <el-table-column label="震级" min-width="150" show-overflow-tooltip align="center" prop="magnitude" />
                <el-table-column label="震源深度" min-width="150" show-overflow-tooltip align="center" prop="focdepth" />
                <el-table-column align="center" min-width="150" label="操作">
                    <template>
                        <el-button type="text" @click="handleFlashPush">
                            推送
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="card-container">
            <div class="body-title">
                <div class="body-title-left">快速预警</div>
            </div>
            <vxe-table show-overflow border="inner" resizable ref="xTable" height="336" align="center" keep-source
                class="mytable-scrollbar" :data="tableData"
                :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true, }" @edit-closed="editClosedEvent">
                <vxe-column field="warningLevelColor" min-width="150" title="设备响应等级">
                    <template #default="{ row }">
                        <span>{{ row.warningLevelColor }}</span>
                    </template>
                </vxe-column>

                <vxe-column field="warningConfigName" min-width="150" title="预警响应规则" :edit-render="{}">
                    <template #default="{ row }">
                        <span>{{ row.warningConfigName == '' ? "自动规则" : row.warningConfigName }}</span>
                    </template>

                    <template #edit="{ row }">
                        <vxe-select v-model="row.warningConfigName" :disabled="row.warningLevelColor == '取消预警'">
                            <vxe-option v-for="(item, index) in warmList" :key="index" :label="item.name"
                                :value="item.name == '自动规则' ? '' : item.name"></vxe-option>
                        </vxe-select>
                    </template>
                </vxe-column>
                <vxe-column field="countdown" min-width="150" title="倒计时" :edit-render="{}">
                    <template #default="{ row }">
                        <span>{{ row.countdown }}</span>
                    </template>
                    <template #edit="{ row }">
                        <vxe-select v-model="row.countdown" :disabled="row.warningLevelColor == '取消预警'">
                            <vxe-option v-for="(item, index) in timeList" :key="index" :label="item"
                                :value="item"></vxe-option>
                        </vxe-select>
                    </template>
                </vxe-column>

                <vxe-column title="操作" min-width="150">
                    <template #default="{ row }">
                        <vxe-button type="text" content="推送" @click="handlePush(row)"></vxe-button>
                    </template>
                </vxe-column>
            </vxe-table>
        </div>
        <div class="card-container">
            <div class="body-title">
                <div class="body-title-left">快速气象</div>
            </div>
            <vxe-table show-overflow ref="xTable" border="inner" height="288px" align="center" keep-source
                class="mytable-scrollbar" :data="weatherData"
                :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true, }" @edit-closed="editClosedEvent">
                <vxe-column field="levelCode" min-width="150" title="设备响应等级">
                    <template #default="{ row }">
                        <span>{{ row.levelCode }}</span>
                    </template>
                </vxe-column>
                <vxe-column field="typeCode" min-width="150" title="气象类型" :edit-render="{}">
                    <template #default="{ row }">
                        <span>{{ row.typeCode }}</span>
                    </template>
                    <template #edit="{ row }">
                        <vxe-select v-model="row.typeCode" :disabled="row.levelCode == '取消预警'">
                            <vxe-option v-for="(item, index) in typeList" :key="index" :label="item"
                                :value="item"></vxe-option>
                        </vxe-select>
                    </template>
                </vxe-column>
                <vxe-column field="hour" min-width="150" title="有效期(小时)" :edit-render="{}">
                    <template #default="{ row }">
                        <span>{{ row.hour }}</span>
                    </template>
                    <template #edit="{ row }">
                        <vxe-select v-model="row.hour" :disabled="row.levelCode == '取消预警'">
                            <vxe-option v-for="(item, index) in weatherHour" :key="index" :label="item"
                                :value="item"></vxe-option>
                        </vxe-select>
                    </template>
                </vxe-column>

                <vxe-column title="操作" min-width="150" fixed="right">
                    <template #default="{ row }">
                        <vxe-button type="text" content="推送" @click="handleWeatherPush(row)"></vxe-button>
                    </template>
                </vxe-column>
            </vxe-table>
        </div>

        <!-- 新增/编辑 -->
        <!-- <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="dialogVisible" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="预警规则" prop="warningConfigName">
                    <el-select style="width:100%" v-model="form.warningConfigName" placeholder="请选择预警配置">
                        <el-option v-for="item in warmList" :key="item.name" :label="item.name"
                            :value="item.name == '自动规则' ? '' : item.name">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="设备预警等级" prop="warningLevelColor">
                    <el-select style="width:100%" v-model="form.warningLevelColor" placeholder="请选择设备预警等级">
                        <el-option v-for="(item, index) in warnLevel" :key="'level' + index" :label="item" :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="倒计时" prop="countdown">
                    <el-input v-model="form.countdown" placeholder="请输入倒计时" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button  @click="submitForm">确 定</el-button>
                <el-button @click="dialogVisible = false">取 消</el-button>
            </div>
        </el-dialog> -->
        <el-dialog :title="'推送进度'" :close-on-click-modal="false" :before-close="pushClose" v-if="pushScheduleOpen"
            :visible.sync="pushScheduleOpen" width="800px" append-to-body>
            <div class="card-container">
                <div class="push-header">
                    <el-progress type="circle" v-show="+(num.toFixed(0)) !== 100"
                        :percentage="+(num.toFixed(0))"></el-progress>
                    <el-result icon="success" v-show="num.toFixed(0) == 100" title="推送完成">
                        <template slot="extra">
                            <el-button size="medium" @click="pushClose">返回列表</el-button>
                        </template>
                    </el-result>
                </div>
            </div>
        </el-dialog>
        <!-- <el-dialog title="推送记录" :close-on-click-modal="false" :visible.sync="pushVisible" append-to-body>
            <div style="display: flex; justify-content: flex-end;
            margin-bottom: 10px;">
                <el-button   :disabled="pushData.length == 0" @click="deletePushLog">删除
                </el-button>
            </div>
            <el-table :data="pushData" height="800" style="width: 100%" border>
                <el-table-column label="推送时间" min-width="150" align="center" prop="pushTime" />
                <el-table-column label="推送人" min-width="150" show-overflow-tooltip align="center" prop="createBy" />
                <el-table-column label="事件报文" min-width="150" show-overflow-tooltip align="center" prop="jsonData">
                    <template slot-scope="scope">
                        <el-button type="text" @click="handleLook(scope.row)">
                            查看
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="推送状态" min-width="150" show-overflow-tooltip align="center" prop="pushStatus" />
            </el-table>
        </el-dialog> -->
        <el-dialog title="报文" append-to-body :visible.sync="jsonVisible" width="30%">
            <json-viewer :value="messageData" :expand-depth="5" copyable boxed expanded sort></json-viewer>
        </el-dialog>
    </div>
</template>

<script>
import {
    getFastWarning,
    fastWeather,
    pushWeather,
    pushLogWeather,
    cancelWeather,
    cancelFastWarning
} from "@/api/allDevice/allDevice";
import {
    getPushIndex,
    handlePush
} from "@/api/rehearsal/index.js";
import VXETable from 'vxe-table'
import { getAddress } from '@/api/rehearsal/index.js';
import { handleAdd, getEewPushIndex, handleEewPush } from '@/api/eewRehearsal/index.js';
import { listLevelWarm } from '@/api/configuration/alertLevel/index.js'
export default {
    dicts: [
        "sys_event_type",
    ],
    props: {
        pageData: {
            type: Object,
            default: {},
        },
    },
    data() {
        return {
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                locname: null,
                createTime: [],
                msgType: "0",
            },
            queryLevelWarm: {
                pageNum: 1,
                pageSize: 10,
                name: null
            },
            flashData: [{
                locname: '随机',
                magnitude: '随机',
                focdepth: '随机',
            }],
            form: {},
            warmList: [],//预警配置列表
            timeList: ['随机', '15', '20', '25', '30', '60'],
            warnLevel: ['无预警', '蓝色预警', '黄色预警', '橙色预警', '红色预警', '取消预警'],
            // pushVisible: false,
            dialogVisible: false,
            title: '',
            total: 0,
            // 表单校验
            rules: {
                // warningConfigName: [{ required: true, message: "预警规则不能为空", trigger: "change" }],
                warningLevelColor: [
                    { required: true, message: "设备预警等级不能为空", trigger: "change" },
                ],
                countdown: [
                    { required: true, message: "倒计时不能为空", trigger: "blur" },
                ],
            },
            pushData: [{
                pushtime: '2023-06-12 15:32:23',
                pushMan: 'admin',
                josn: '',
                status: '成功'
            }],
            typeList: ['随机', '台风', '暴雨', '暴雪', '寒潮', '大风', '沙尘暴', '高温', '干旱', '雷电', '冰雹', '霜冻', '大雾', '霾', '道路结冰'],
            weatherHour: ['随机', '1', '3', '6', '12', '24'],
            weatherData: [
                { typeCode: '随机', levelCode: '蓝色预警', hour: '随机' },
                { typeCode: '随机', levelCode: '黄色预警', hour: '随机' },
                { typeCode: '随机', levelCode: '橙色预警', hour: '随机' },
                { typeCode: '随机', levelCode: '红色预警', hour: '随机' },
                { typeCode: '', levelCode: '取消预警', hour: '' }],
            tableData: [{ warningConfigName: '', warningLevelColor: '无预警', countdown: '随机' },
            { warningConfigName: '', warningLevelColor: '蓝色预警', countdown: '随机' },
            { warningConfigName: '', warningLevelColor: '黄色预警', countdown: '随机' },
            { warningConfigName: '', warningLevelColor: '橙色预警', countdown: '随机' },
            { warningConfigName: '', warningLevelColor: '红色预警', countdown: '随机' }, { warningConfigName: null, warningLevelColor: '取消预警', countdown: '' }],

            pushScheduleOpen: false,
            num: 0,
            timer: null,
            messageData: {},
            jsonVisible: false,
            pushId: '',
            paramData: {},
        }
    },
    created() {
        this.listLevelWarm()
        // this.getList()
    },
    beforeDestroy() {
        clearTimeout(this.timer);
    },
    methods: {
        // 获取预警配置列表
        async listLevelWarm() {
            const res = await listLevelWarm(this.queryLevelWarm);
            if (res.code == 200) {
                let obj = {
                    name: '自动规则'
                }
                this.warmList = res.rows || []
                this.warmList.unshift(obj)
                console.log(this.warmList, 'this.warmList')
            }
        },
        // 失焦事件
        async editClosedEvent({ row, column }) {
            const $table = this.$refs.xTable
            const { insertRecords } = $table.getRecordset()
        },

        formatlevel(val) {
            switch (val) {
                case '无预警':
                    return '无预警（灰色）'
                case 'Ⅳ级':
                    return '蓝色预警'
                case 'Ⅲ级':
                    return '黄色预警'
                case 'Ⅱ级':
                    return '橙色预警'
                case 'Ⅰ级':
                    return '红色预警'
                default:
                    break;
            }
        },
        // 新增
        async handleAdd() {
            this.listLevelWarm()
            this.title = '新增'
            this.$refs.form && this.$refs.form.resetFields();
            this.dialogVisible = true
            this.form = {
                warningConfigName: '',
                warningLevelColor: null,
                countdown: null,
                deviceId: this.pageData.deviceId
            };
        },

        // 提交按钮
        // submitForm() {
        //     this.$refs["form"].validate(async (valid) => {
        //         if (valid) {
        //             if (this.title == '新增') {
        //                 const res = await addFastWarning(this.form)
        //                 if (res.code == 200) {
        //                     this.$modal.msgSuccess('新增成功');
        //                 } else {
        //                     this.$modal.msgError('新增失败');
        //                 }
        //             } else {
        //                 const res = await updateFastWarning(this.form)
        //                 if (res.code == 200) {
        //                     this.$modal.msgSuccess('修改成功');
        //                 } else {
        //                     this.$modal.msgError('修改失败');
        //                 }
        //             }
        //             this.dialogVisible = false
        //             this.getList()
        //         }
        //     })

        // },
        // 删除
        // async handleDel(row) {
        //     const res = await delFastWarning(row.id)
        //     if (res.code == 200) {
        //         this.$modal.msgSuccess('删除成功');
        //         this.getList()
        //     }
        // },

        // 编辑
        // async handleEdit(row) {
        //     this.listLevelWarm()
        //     this.title = '编辑'
        //     this.dialogVisible = true
        //     this.form = row
        // },
        // 推送
        async handlePush(row) {
            if (row.warningLevelColor == '取消预警') {

                const rescancel = await cancelFastWarning(this.pageData.code)
                if (rescancel.code == 200) {
                    this.$modal.msgSuccess('取消预警成功');
                }
                return
            }
            let param = {
                deviceId: this.pageData.deviceId,
                warningConfigName: row.warningConfigName,
                warningLevelColor: row.warningLevelColor
            }
            if (row.countdown == '随机') {
                param.countdown = (Math.random() * 10 + 20).toFixed(0)
            } else {
                param.countdown = row.countdown
            }
            this.num = 0
            this.pushScheduleOpen = true;
            this.timer = setInterval(() => {
                if (this.num >= 95) {
                    return
                }
                this.num += 5
            }, 100)
            const res = await getFastWarning(param)
            if (res.code == 200) {
                const res1 = await getPushIndex({ msgId: res.data.msgId });
                if (res1.code == 200) {
                    const res2 = await handlePush({
                        msgId: res.data.msgId,
                        code: this.pageData.code,
                        deviceId: this.pageData.deviceId,
                        drillPushTotalId: res1.data,
                    });
                    clearInterval(this.timer)
                    if (res2.code == 200) {
                        this.num = 100
                    }
                }
            }
        },

        async handleWeatherPush(row) {
            if (row.levelCode == '取消预警') {
                const rescancel = await cancelWeather(this.pageData.code)
                if (rescancel.code == 200) {
                    this.$modal.msgSuccess('取消预警成功');
                }
                return
            }
            let param = {
                deviceId: this.pageData.deviceId,
                levelCode: this.formatlevel(row.levelCode),
            }
            if (row.typeCode == '随机') {
                let _code = Math.ceil(Math.random() * 14)
                console.log(_code, '_code')
                param.typeCode = _code >= 10 ? _code : '0' + _code
            } else {
                param.typeCode = this.formatType(row.typeCode)
            }
            if (row.hour == '随机') {
                param.hour = (Math.random() * 23 + 1).toFixed(0)
            } else {
                param.hour = row.hour
            }
            this.num = 0
            this.pushScheduleOpen = true;
            this.timer = setInterval(() => {
                if (this.num >= 95) {
                    return
                }
                this.num += 5
            }, 100)

            const res = await fastWeather(param)
            if (res.code == 200) {
                const res1 = await pushWeather({ weatherWarningId: res.data.id });
                if (res1.code == 200) {
                    const res2 = await pushLogWeather({
                        weatherWarningId: res.data.id,
                        code: this.pageData.code,
                        deviceId: this.pageData.deviceId,
                        drillPushTotalId: res1.data,
                    });
                    clearInterval(this.timer)
                    if (res2.code == 200) {
                        this.num = 100
                    }
                }
            }
        },
        formatlevel(val) {
            switch (val) {
                case '蓝色预警':
                    return '01'
                case '黄色预警':
                    return '02'
                case '橙色预警':
                    return '03'
                case '红色预警':
                    return '04'
                default:
                    break;
            }
        },

        formatType(val) {
            switch (val) {
                case '台风':
                    return '01';
                case '暴雨':
                    return '02';
                case '暴雪':
                    return '03';
                case '寒潮':
                    return '04';
                case '大风':
                    return '05';
                case '沙尘暴':
                    return '06';
                case '高温':
                    return '07';
                case '干旱':
                    return '08';
                case '雷电':
                    return '09';
                case '冰雹':
                    return '10';
                case '霜冻':
                    return '11';
                case '大雾':
                    return '12';
                case '霾':
                    return '13';
                case '道路结冰':
                    return '14';
                default:
                    break;
            }
        },

        // 随机生成中国经纬度
        getRandomChinaCoordinate() {
            // 中国经度范围
            var minLng = 90;
            var maxLng = 120;
            // 中国纬度范围
            var minLat = 15;
            var maxLat = 50;
            // 生成随机经度
            var longitude = (Math.random() * (maxLng - minLng) + minLng).toFixed(6);
            // 生成随机纬度
            var latitude = (Math.random() * (maxLat - minLat) + minLat).toFixed(6);
            this.getAddress(longitude, latitude)
        },
        async getAddress(lon, lat) {
            const res = await getAddress(lon, lat)
            if (res.code == 200) {
                if (res.msg == '' || res.msg == null) {
                    return this.getRandomChinaCoordinate()
                }
                // 随机生成规则
                let magnitude = Math.random() * 3 + 3
                let focdepth = Math.random() * 15 + 10
                this.paramData = {
                    epiintensity: this.formatIntensity(magnitude),
                    epilon: lon,
                    epilat: lat,
                    locname: res.msg,
                    deviceId: [this.pageData.deviceId],
                    magnitude: magnitude.toFixed(1),
                    focdepth: Math.ceil(focdepth),
                }
                this.handleAdd()
            }
        },
        formatIntensity(val) {
            if (val <= 1.5) {
                return 0;
            } else {
                return Math.floor((val - 1.5) / 0.58);
            }
        },
        async handleAdd() {
            const res = await handleAdd(this.paramData);
            if (res.code == 200) {
                this.getPushIndex(res.data.msgId)
            }
        },
        async getPushIndex(msgId) {
            const res = await getEewPushIndex({ msgId: msgId });
            if (res.code == 200) {
                this.handlePush1(msgId, res.data)
            }
        },
        async handlePush1(msgId, drillPushTotalId) {
            const res = await handleEewPush({
                msgId: msgId,
                code: this.pageData.code,
                deviceId: this.pageData.deviceId,
                drillPushTotalId: drillPushTotalId,
            });
            clearInterval(this.timer)
            if (res.code == 200) {
                this.num = 100
            }
        },

        handleFlashPush() {
            this.num = 0
            this.pushScheduleOpen = true;
            this.timer = setInterval(() => {
                if (this.num == 95) {
                    return
                }
                this.num += 5
            }, 100)
            this.getRandomChinaCoordinate()
        },
        pushClose() {
            this.pushScheduleOpen = false;
        },
        // async deletePushLog() {
        //     const res = await deletePushLog(this.pushId)
        //     if (res.code == 200) {
        //         this.$modal.msgSuccess('删除成功');
        //         this.getPushLog()
        //     }
        // },
        // 查看报文
        handleLook(row) {
            this.jsonVisible = true
            if (row.jsonData?.indexOf('{') != -1) {
                this.messageData = JSON.parse(row.jsonData)
            } else {
                this.messageData = row.jsonData
            }
        },
    }
}
</script>

<style lang="scss" scoped>
#push-page {
    height: 750px;
    padding: 0 20px;
    overflow: auto;
}

.body-title {
    display: flex;
    position: relative;
    // justify-content: space-between;
    align-items: center;
}

.body-title-left {
    height: 100%;
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 600;
    color: #fff;
    line-height: 64px;
}

.body-title-right {
    position: absolute;
    right: 0;
}

.eewMessage {
    >div {
        display: flex;
        text-align: left;
    }
}

::v-deep .custom-tree-node {
    >span {
        color: var(--inputColor);
    }
}

::v-deep .el-tree-node__content {
    white-space: pre-wrap;
    text-align: left;
    height: 100%;
}

::v-deep .el-tree-node__content:hover,
.el-upload-list__item:hover {
    background: rgba(255, 255, 255, 0.3);
    color: #0095ff;
}

::v-deep .el-tree-node:focus>.el-tree-node__content {
    background: rgba(0, 149, 255, 0.1);
}


.push-header {
    display: flex;
    justify-content: center;
}
</style>